package com.idbk.chargestation.bean;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.annotations.SerializedName;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 电桩资费策略
 *
 * @author liangzw, lupc, zhx
 */
public class JsonPileTariff implements Parcelable {

    /**
     * 服务收费方式：按次收费
     */
    public final static int SERVICE_ENUM_COUNT = 1;
    /**
     * 服务收费方式：按时间收费
     */
    public final static int SERVICE_ENUM_TIME = 2;
    /**
     * 服务收费方式：按电量收费
     */
    public final static int SERVICE_ENUM_POWER = 3;

    @SerializedName("id")
    public int id;//点赞数

    @SerializedName("agentId")
    public int agentId;//代理商Id

    @SerializedName("priceName")
    public String priceName;//电价名称

    @SerializedName("servicePrice")
    public int servicePrice;//服务费

    @SerializedName("serviceTypeEnum")
    public int serviceTypeEnum;//服务类型

    /**
     * 尖峰电价，实际情况需要除以100，编号为1
     */
    @SerializedName("price1")
    public int price1;//尖峰电价

    @SerializedName("price2")
    public int price2;//高峰电价

    @SerializedName("price3")
    public int price3;//平谷电价

    @SerializedName("price4")
    public int price4;//低谷电价

    /**
     * 通用电价
     * 需要除以100处理
     */
    @SerializedName("priceCommon")
    public double priceCommon;

	/*  以下是各个时段的划分以及对应的电价
     *  注意：
	 *  	1.如果只有4个时段，则第5个开始的时段为null
	 *  	2.电价标号 表示 对应的 price1-4
	 *   
	 *   */

    /**
     * 时段1开始时间点
     */
    @SerializedName("time1StartAt")
    public String time1StartAt;

    /**
     * 电价标号
     */
    @SerializedName("time1PriceCode")
    public int time1PriceCode;

    @SerializedName("time2StartAt")
    public String time2StartAt;

    @SerializedName("time2PriceCode")
    public int time2PriceCode;

    @SerializedName("time3StartAt")
    public String time3StartAt;

    @SerializedName("time3PriceCode")
    public int time3PriceCode;

    @SerializedName("time4StartAt")
    public String time4StartAt;

    @SerializedName("time4PriceCode")
    public int time4PriceCode;

    @SerializedName("time5StartAt")
    public String time5StartAt;

    @SerializedName("time5PriceCode")
    public int time5PriceCode;

    @SerializedName("time6StartAt")
    public String time6StartAt;

    @SerializedName("time6PriceCode")
    public int time6PriceCode;

    @SerializedName("time7StartAt")
    public String time7StartAt;

    @SerializedName("time7PriceCode")
    public int time7PriceCode;

    @SerializedName("time8StartAt")
    public String time8StartAt;

    @SerializedName("time8PriceCode")
    public int time8PriceCode;

    @SerializedName("time9StartAt")
    public String time9StartAt;

    @SerializedName("time9PriceCode")
    public int time9PriceCode;

    @SerializedName("time10StartAt")
    public String time10StartAt;

    @SerializedName("time10PriceCode")
    public int time10PriceCode;

    @SerializedName("time11StartAt")
    public String time11StartAt;

    @SerializedName("time11PriceCode")
    public int time11PriceCode;

    @SerializedName("time12StartAt")
    public String time12StartAt;

    @SerializedName("time12PriceCode")
    public int time12PriceCode;

    public int[] priceCode;

    public String[] timeSpans;

    @SerializedName("parkingFee")
    public int parkingFee;

    @SerializedName("isFree")
    public boolean isFree;

    @SerializedName("freeTime")
    public int freeTime;

    @SerializedName("servicePrice1")
    public int servicePrice1;

    @SerializedName("servicePrice2")
    public int servicePrice2;

    @SerializedName("servicePrice3")
    public int servicePrice3;

    @SerializedName("servicePrice4")
    public int servicePrice4;

    @SerializedName("enableOnePrice")
    public boolean enableOnePrice;

    @SerializedName("enableUpdateNow")
    public boolean enableUpdateNow;

    /**
     * 获取通用电价（元）
     *
     * @return
     */
    public String getCommonPriceString() {
        return String.format(Locale.CHINA, "%.2f", priceCommon / 100d);
    }

    /**
     * 获取服务类型 字符串
     *
     * @return
     */
    public String getServiceTypeString() {
        String price = String.format(Locale.CHINA, "%.2f", servicePrice / 100d);
        if (serviceTypeEnum == SERVICE_ENUM_COUNT) {
            return "按次收费，" + price + "元/次";
        } else if (serviceTypeEnum == SERVICE_ENUM_TIME) {
            return "按时间收费，" + price + "元/10分钟";
        } else if (serviceTypeEnum == SERVICE_ENUM_POWER) {
            return "按电量收费，" + price + "元/度";
        } else {
            return "N/A";
        }
    }

    public String getServiceType() {

        if (serviceTypeEnum == SERVICE_ENUM_COUNT) {
            return "元/次";
        } else if (serviceTypeEnum == SERVICE_ENUM_TIME) {
            return "元/10分钟" ;
        } else if (serviceTypeEnum == SERVICE_ENUM_POWER) {
            return "元/度";
        } else {
            return "N/A";
        }
    }

    /**
     * 获取分时段 的电价
     *
     * @param index 电价标号
     * @return 分时段 的电价
     */
    public String getSplitTimePriceInfo(int index) {
        if (index == 1) {
            return String.format(Locale.CHINA, "%.2f", price1 / 100d);
        } else if (index == 2) {
            return String.format(Locale.CHINA, "%.2f", price2 / 100d);
        } else if (index == 3) {
            return String.format(Locale.CHINA, "%.2f", price3 / 100d);
        } else if (index == 4) {
            return String.format(Locale.CHINA, "%.2f", price4 / 100d);
        } else {
            return "N/A";
        }
    }

    /**
     * 获取分时段 的电价
     *
     * @param index 电价标号
     * @return 分时段 的电价
     */
    public String getSplitTimeServicePriceInfo(int index) {
        String price;
        if (index == 1) {
            price = String.format(Locale.CHINA, "%.2f", servicePrice1 / 100d);
        } else if (index == 2) {
            price = String.format(Locale.CHINA, "%.2f", servicePrice2 / 100d);
        } else if (index == 3) {
            price = String.format(Locale.CHINA, "%.2f", servicePrice3 / 100d);
        } else if (index == 4) {
            price = String.format(Locale.CHINA, "%.2f", servicePrice4 / 100d);
        } else {
            return "N/A";
        }
        return price;
    }

    public String getServiceUnit() {
        switch (serviceTypeEnum) {
            case JsonPileTariff.SERVICE_ENUM_COUNT:
                return "元/次";
            case JsonPileTariff.SERVICE_ENUM_TIME:
                return "元/10分钟";
            case JsonPileTariff.SERVICE_ENUM_POWER:
                return "元/度";
            default:
                return "元/次";
        }
    }


    /**
     * 由于服务器给的 包含年月日的时间字符串，这里需要截取 小时和分 相关的字符
     * 1970-01-01 00:00:00
     *
     * @param splitTime 服务器给的 包含年月日的时间字符串
     * @return String 截取 小时和分 相关的字符
     */
    public String getSplitTimeString(String splitTime) {
        int maxLength = 17;
        if (splitTime == null || splitTime.length() < maxLength) {
            return "格式错误";
        } else {
            return splitTime.substring(11, 16);
        }
    }

    public JsonPileTariff() {

    }

    public JsonPileTariff(Parcel in) {
        id = in.readInt();
        agentId = in.readInt();
        priceName = in.readString();
        servicePrice = in.readInt();
        serviceTypeEnum = in.readInt();
        price1 = in.readInt();
        price2 = in.readInt();
        price3 = in.readInt();
        price4 = in.readInt();
        priceCommon = in.readDouble();
        time1StartAt = in.readString();
        time2StartAt = in.readString();
        time3StartAt = in.readString();
        time4StartAt = in.readString();
        time5StartAt = in.readString();
        time6StartAt = in.readString();
        time7StartAt = in.readString();
        time8StartAt = in.readString();
        time9StartAt = in.readString();
        time10StartAt = in.readString();
        time11StartAt = in.readString();
        time12StartAt = in.readString();
        time1PriceCode = in.readInt();
        time2PriceCode = in.readInt();
        time3PriceCode = in.readInt();
        time4PriceCode = in.readInt();
        time5PriceCode = in.readInt();
        time6PriceCode = in.readInt();
        time7PriceCode = in.readInt();
        time8PriceCode = in.readInt();
        time9PriceCode = in.readInt();
        time10PriceCode = in.readInt();
        time11PriceCode = in.readInt();
        time12PriceCode = in.readInt();
        parkingFee = in.readInt();
        boolean[] a = new boolean[1];
        in.readBooleanArray(a);
        isFree = a[0];
        freeTime = in.readInt();
        servicePrice1 = in.readInt();
        servicePrice2 = in.readInt();
        servicePrice3 = in.readInt();
        servicePrice4 = in.readInt();
        boolean[] b = new boolean[1];
        in.readBooleanArray(b);
        enableOnePrice = a[0];
        boolean[] c = new boolean[1];
        in.readBooleanArray(c);
        enableUpdateNow = a[0];
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeInt(agentId);
        dest.writeString(priceName);
        dest.writeInt(servicePrice);
        dest.writeInt(serviceTypeEnum);
        dest.writeInt(price1);
        dest.writeInt(price2);
        dest.writeInt(price3);
        dest.writeInt(price4);
        dest.writeDouble(priceCommon);
        dest.writeString(time1StartAt);
        dest.writeString(time2StartAt);
        dest.writeString(time3StartAt);
        dest.writeString(time4StartAt);
        dest.writeString(time5StartAt);
        dest.writeString(time6StartAt);
        dest.writeString(time7StartAt);
        dest.writeString(time8StartAt);
        dest.writeString(time9StartAt);
        dest.writeString(time10StartAt);
        dest.writeString(time11StartAt);
        dest.writeString(time12StartAt);
        dest.writeInt(time1PriceCode);
        dest.writeInt(time2PriceCode);
        dest.writeInt(time3PriceCode);
        dest.writeInt(time4PriceCode);
        dest.writeInt(time5PriceCode);
        dest.writeInt(time6PriceCode);
        dest.writeInt(time7PriceCode);
        dest.writeInt(time8PriceCode);
        dest.writeInt(time9PriceCode);
        dest.writeInt(time10PriceCode);
        dest.writeInt(time11PriceCode);
        dest.writeInt(time12PriceCode);
        dest.writeInt(parkingFee);
        boolean[] a = new boolean[1];
        a[0] = isFree;
        dest.writeBooleanArray(a);
        dest.writeInt(freeTime);
        dest.writeInt(servicePrice1);
        dest.writeInt(servicePrice2);
        dest.writeInt(servicePrice3);
        dest.writeInt(servicePrice4);
        boolean[] b = new boolean[1];
        b[0] = enableOnePrice;
        dest.writeBooleanArray(b);
        boolean[] c = new boolean[1];
        c[0] = enableUpdateNow;
        dest.writeBooleanArray(c);
    }

    public final static Parcelable.Creator<JsonPileTariff> CREATOR = new Creator<JsonPileTariff>() {

        @Override
        public JsonPileTariff[] newArray(int size) {
            return new JsonPileTariff[size];
        }

        @Override
        public JsonPileTariff createFromParcel(Parcel source) {
            return new JsonPileTariff(source);
        }
    };

    private void initArray() {
        timeSpans = new String[]{
                time1StartAt, time2StartAt, time3StartAt,
                time4StartAt, time5StartAt, time6StartAt,
                time7StartAt, time8StartAt, time9StartAt,
                time10StartAt, time11StartAt, time12StartAt,
        };
        priceCode = new int[]{
                time1PriceCode, time2PriceCode, time3PriceCode,
                time4PriceCode, time5PriceCode, time6PriceCode,
                time7PriceCode, time8PriceCode, time9PriceCode,
                time10PriceCode, time11PriceCode, time12PriceCode,
        };

    }


    /**
     * 获取当前时间时段的电价
     */
    public String compareTime() {
        String result = "0.00";
        String currentTime = getCurrentTime();

        if (timeSpans == null || priceCode == null) {
            initArray();
        }

        for (int number = 0; number < timeSpans.length; number++) {
            String tariffTime = getSplitTimeString(timeSpans[number]);
            if (currentTime.compareTo(tariffTime) > 0) {
                boolean isEnd = ((number + 1) >= timeSpans.length)
                        || (((number + 1) < timeSpans.length)) && (timeSpans[number + 1] == null);
                if (isEnd) {
                    result = getSplitTimePriceInfo(priceCode[number]);
                    return result;
                }
            } else {
                if (number > 0) {
                    result = getSplitTimePriceInfo(priceCode[number - 1]);
                } else {
                    result = getSplitTimePriceInfo(priceCode[number]);
                }
                return result;
            }
        }
        return result;
    }

    /**
     * 获取当前时间时段的服务费
     */
    public String getServicePrice() {
        String result = "0.00";
        String currentTime = getCurrentTime();

        if (timeSpans == null || priceCode == null) {
            initArray();
        }

        for (int number = 0; number < timeSpans.length; number++) {
            String tariffTime = getSplitTimeString(timeSpans[number]);
            if (currentTime.compareTo(tariffTime) > 0) {
                boolean isEnd = ((number + 1) >= timeSpans.length)
                        || (((number + 1) < timeSpans.length)) && (timeSpans[number + 1] == null);
                if (isEnd) {
                    result = getSplitTimeServicePriceInfo(priceCode[number]);
                    return result;
                }
            } else {
                if (number > 0) {
                    result = getSplitTimeServicePriceInfo(priceCode[number - 1]);
                } else {
                    result = getSplitTimeServicePriceInfo(priceCode[number]);
                }
                return result;
            }
        }
        return result;
    }

    private String getCurrentTime() {
        Calendar calendar = Calendar.getInstance();
        String hour = String.format(Locale.CHINA, "%02d", calendar.get(Calendar.HOUR_OF_DAY));
        String minute = String.format(Locale.CHINA, "%02d", calendar.get(Calendar.MINUTE));
        return hour + ":" + minute;
    }

    public String timePrices() {
        StringBuffer sb = new StringBuffer("");

        if (timeSpans == null || priceCode == null) {
            initArray();
        }

        for (int i = 0; i < timeSpans.length; i++) {
            if (timeSpans[0] == null) {
                break;
            }
            //最后一个
            if (i == timeSpans.length - 1) {
                String start = getSplitTimeString(timeSpans[i]);
                String end = "24:00";
                appendPriceInfo(sb, start, end, priceCode[i]);
            } else {
                if (timeSpans[i + 1] == null) {
                    String start = getSplitTimeString(timeSpans[i]);
                    String end = "24:00";
                    appendPriceInfo(sb, start, end, priceCode[i]);
                    break;
                } else {
                    String start = getSplitTimeString(timeSpans[i]);
                    String end = getSplitTimeString(timeSpans[i + 1]);
                    appendPriceInfo(sb, start, end, priceCode[i]);
                    sb.append("<br/>");
                }
            }
        }
        return sb.toString();
    }

    private void appendPriceInfo(StringBuffer sb, String start, String end, int priceIndex) {
        //判断当前时间是否在这个范围内
        boolean result = isCurrentTimeSpan(start, end);
        if (result) {
            sb.append("<font color='#ffffff'>");
            sb.append(start);
            sb.append("-");
            sb.append(end);
            sb.append(" ");
            sb.append(getSplitTimePriceInfo(priceIndex));
            sb.append("元/度</font>");
        } else {
            sb.append("<font color='#a0a0a0'>");
            sb.append(start);
            sb.append("-");
            sb.append(end);
            sb.append(" ");
            sb.append(getSplitTimePriceInfo(priceIndex));
            sb.append("元/度</font>");
        }
    }

    private boolean isCurrentTimeSpan(String start, String end) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.CHINESE);
        String now = sdf.format(new Date());

        boolean result;
        int startTime = 0;
        int endTime = 0;
        int nowTime = 0;
        try {
            startTime = Integer.parseInt(start.replace(':', '0'));
            endTime = Integer.parseInt(end.replace(':', '0'));
            nowTime = Integer.parseInt(now.replace(':', '0'));
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }

        if (result && nowTime <= endTime && nowTime >= startTime) {
            result = true;
        } else {
            result = false;
        }
        return result;
    }

}
